{% extends "business/business_base.html" %}
{% block head %} 
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-table.min.css') }}">
<style type="text/css">
.pre {display: inline-block;width: 172px;height: 160px;margin: 0 20px 0 0;}
.pre img {border-radius: 5px;width: 172px;height: 110px;}
.pre div {color: #3D3D3D;font-size: 13px;width: 170px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}
.pre div > a {float: right;}
</style>
{% endblock %}
{% block title %}{{ title }}{% endblock %}
{% block page_content %}

{{ super() }}
<h1 class="page-header">{{ title }}</h1>
<div class="col-md-12">
	<button type="button" style="margin-bottom:15px" class="btn btn-success" data-target="#AddModal" data-toggle="modal">新增业务</button>
	<table id="tb" data-use-row-attr-func="true" data-reorderable-rows="true" ></table>
</div>
<div class="modal fade" id="AddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
	<div class="modal-dialog" style="height:400px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">新增业务</h4>
			</div>
			<div class="modal-body">
				<div class="row">
					<span class="col-md-2" style="margin-top:5px;"><center>业务名称</center></span>
    					<input class="col-md-8" type="text" id="name"  name="name" autocomplete="off" >
				</div>
				<div class="row" style="margin-top:30px;">
					<span class="col-md-2" style="margin-top:5px;"><center>业务简介</center></span>
    					<input type="text" class="col-md-8" id="info" name="info" autocomplete="off" >
	 			</div>
				<div class="row" style="margin-top:30px;">
					<span class="col-md-2" style="margin-top:5px;"><center>业务介绍</center></span>
    					<textarea type="text" style="height:80px;" class="col-md-8" id="details" name="details" autocomplete="off" ></textarea>
	 			</div>
				<div class="row" style="margin-top:30px;">
					<span class="col-md-2" style="margin-top:5px;"><center>业务图片</center></span>
					<div class="col-md-offset-2">
						<div id="pic_pre"></div>
						<div>
							<button id="pic_pick" class="btn btn-success">选择文件</button>
						</div>
					</div>
 				</div>
				<input type="hidden" id="btype" name="btype" value="{{ btype }}" >
				<button type="submit" class="btn btn-default" onclick="add_submit()">保存</button>
			</div>	
		</div>
	</div>
</div>

<div class="modal fade" id="EditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
	<div class="modal-dialog" style="height:400px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">编辑业务</h4>
			</div>
			<div class="modal-body">
				<div class="row">
					<span class="col-md-2" style="margin-top:5px;"><center>业务名称</center></span>
    					<input class="col-md-8" type="text" id="name_e" autocomplete="off" required>
				</div>
				<div class="row" style="margin-top:30px;">
					<span class="col-md-2" style="margin-top:5px;"><center>业务简介</center></span>
    					<input type="text" class="col-md-8" id="info_e" autocomplete="off" required>
	 			</div>
				<div class="row" style="margin-top:30px;">
					<span class="col-md-2" style="margin-top:5px;"><center>业务介绍</center></span>
    					<textarea type="text" style="height:80px;" class="col-md-8" id="details_e" autocomplete="off" required></textarea>
	 			</div>
				<div class="row" style="margin-top:30px;">
					<span class="col-md-2" style="margin-top:5px;"><center>业务图片</center></span>
					<div class="col-md-offset-2">
						<div id="pic_pre_e">
							<div style="display:inline-block;margin-right:20px;margin-bottom:10px;">
								<img id="pic_e" style="border-radius:5px;width:176px;height:110px;" src="/static/img/loading.gif">
							</div>
						</div>
						<div>
							<button id="pic_pick_e" class="btn btn-success">选择文件</button>
						</div>
					</div>
 				</div>
				<input type="hidden" id="bid" name="bid">
				<button type="submit" class="btn btn-default" onclick="edit_submit()">保存</button>
			</div>	
		</div>
	</div>
</div>
<div class="modal fade" id="DeleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">删除业务</h4>
			</div>
			<div class="modal-body">
				<center>确定删除该业务吗？</center>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-danger" onclick="Del()">确定</button>
				<button type="button" class="btn btn-success" data-dismiss="modal" aria-hidden="true">取消</button>
			</div> 
		</div>
	</div><!-- /.modal-dialog -->
</div>

{% endblock %}
{% block scripts  %}
{{ super() }}
<script src="{{ url_for('static', filename='js/bootstrap-table.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap-table-zh-CN.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/jquery.tablednd.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap-table-reorder-rows.js') }}"></script>
<script src="{{ url_for('static', filename='js/qiniu.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/plupload.full.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/jquery.plupload.queue.js') }}"></script>

<script>
var pic = '';
var pic_e = '';
var uploader = Qiniu.uploader({
	runtimes: 'html5,flash,html4',      // 上传模式，依次退化
	browse_button: 'pic_pick',         // 上传选择的点选按钮，必需
	uptoken_url: '/auth/uptoken/',      // Ajax请求uptoken的Url，强烈建议设置（服务端提供）
	unique_names: false,		    // 默认 false，key为文件名。若开启该选项，SDK为自动生成上传成功后的key（文件名）。
	save_key: false, 		    // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK会忽略对key的处理
	filters: {
		mime_types: [{
				title: "Image files", extensions: "jpg,jpeg,png"
		}]
	},
	domain: 'http://omdcfjxex.bkt.clouddn.com/',   //bucket 域名，下载资源时用到，**必需**
	get_new_uptoken: false,  	    //设置上传文件的时候是否每次都重新获取新的token
	max_file_size: '5mb',              // 最大文件体积限制
	flash_swf_url: '/static/js/Moxie.swf',  //引入flash，相对路径
	max_retries: 3,                     // 上传失败最大重试次数
	dragdrop: true,                     // 开启可拖曳上传
	chunk_size: '4mb',                  // 分块上传时，每块的体积
	auto_start: true,                   // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
	multi_selection: false,		    // 只能单选
	init: {
		'FilesAdded': function(up, files) {
			plupload.each(files, function(file) {
			// 文件添加进队列后，处理相关的事情
			});
		},
		'BeforeUpload': function(up, file) {
      			// 每个文件上传前，处理相关的事情
		  	var pic_pre = document.getElementById('pic_pre');
			pic_pre.innerHTML = '<div style="display:inline-block;margin-right:20px;margin-bottom:10px;">'+
					'<img id="pic" style="border-radius:5px;width:176px;height:110px;" src="/static/img/loading.gif">'+
					'</div>';
			},
		'UploadProgress': function(up, file) {
             		// 每个文件上传时，处理相关的事情
		},
		'FileUploaded': function (up, file, info){
			var info = $.parseJSON(info);
			var domain = up.getOption('domain');
			$('#pic').attr('src', domain + info['key'] + '?imageView2/1/w/176/h/110');
			pic = info['key'];
                    },
		'Error': function(up, err, errTip) {
			//上传出错时，处理相关的事情
		},
		'UploadComplete': function() {
            	//队列文件处理完毕后，处理相关的事情
		},
		'Key': function (up, file) {
                        // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                        // 该配置必须要在 unique_names: false , save_key: false 时才生效
			ext = Qiniu.getFileExtension(file.name);
			file_name = (new Date()).valueOf();
			var key = file_name + "." + ext;
			// do something with key here
			return key;
		}
    }
});

var uploader_e = Qiniu.uploader({
	runtimes: 'html5,flash,html4',      // 上传模式，依次退化
	browse_button: 'pic_pick_e',         // 上传选择的点选按钮，必需
	uptoken_url: '/auth/uptoken/',      // Ajax请求uptoken的Url，强烈建议设置（服务端提供）
	unique_names: false,		    // 默认 false，key为文件名。若开启该选项，SDK为自动生成上传成功后的key（文件名）。
	save_key: false, 		    // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK会忽略对key的处理
	filters: {
		mime_types: [{
				title: "Image files", extensions: "jpg,jpeg,png"
		}]
	},
	domain: 'http://omdcfjxex.bkt.clouddn.com/',   //bucket 域名，下载资源时用到，**必需**
	get_new_uptoken: false,  	    //设置上传文件的时候是否每次都重新获取新的token
	max_file_size: '5mb',              // 最大文件体积限制
	flash_swf_url: '/static/js/Moxie.swf',  //引入flash，相对路径
	max_retries: 3,                     // 上传失败最大重试次数
	dragdrop: true,                     // 开启可拖曳上传
	chunk_size: '4mb',                  // 分块上传时，每块的体积
	auto_start: true,                   // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
	multi_selection: false,		    // 只能单选
	init: {
		'FilesAdded': function(up, files) {
			plupload.each(files, function(file) {
			// 文件添加进队列后，处理相关的事情
			});
		},
		'BeforeUpload': function(up, file) {
      			// 每个文件上传前，处理相关的事情
		  	var pic_pre_e = document.getElementById('pic_pre_e');
			pic_pre_e.innerHTML = '<div style="display:inline-block;margin-right:20px;margin-bottom:10px;">'+
					'<img id="pic_e" style="border-radius:5px;width:176px;height:110px;" src="/static/img/loading.gif">'+
					'</div>';
			},
		'UploadProgress': function(up, file) {
             		// 每个文件上传时，处理相关的事情
		},
		'FileUploaded': function (up, file, info){
			var info = $.parseJSON(info);
			var domain = up.getOption('domain');
			$('#pic_e').attr('src', domain + info['key'] + '?imageView2/1/w/176/h/110');
			pic_e = info['key'];
                    },
		'Error': function(up, err, errTip) {
			//上传出错时，处理相关的事情
		},
		'UploadComplete': function() {
            	//队列文件处理完毕后，处理相关的事情
		},
		'Key': function (up, file) {
                        // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                        // 该配置必须要在 unique_names: false , save_key: false 时才生效
			ext = Qiniu.getFileExtension(file.name);
			file_name = (new Date()).valueOf();
			var key = file_name + "." + ext;
			// do something with key here
			return key;
		}
    }
});
</script>

<script>

var drag_prev, drag_next;
var drop_prev, drop_next;
var selected_row, selected_index;

$(function () {

    //初始化Table
    var table = new TableInit();
    table.Init();
});


var TableInit = function () {
    var oTableInit = new Object();
    oTableInit.Init = function () {
    
   	 //初始化Table
        $("#tb").bootstrapTable({
            url: "/business/other/get_list/?btype={{ btype }}",  //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: false,                 //是否显示列选择
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            columns: [{
		field: 'order',
		title: '序号',
		align: 'center',
		valign: 'middle',
	    },{
                field: 'name',
                title: '业务名称',
		align: 'center',
		valign: 'middle',
            }, {
                field: 'picture',
                title: '业务图片',
		align: 'center',
		valign: 'middle',
		formatter: function(value, row, index) {
		        	return '<img style="width:300px;height:200px;border-radius:5px;" src="' + value + '"/>';
		},
            }, {
                field: 'info',
                title: '业务简介',
		align: 'center',
		valign: 'middle',
            }, {
                field: 'details',
                title: '业务内容',
		align: 'center',
		valign: 'middle',
            },{
                field: 'operate',
                title: '操作',
                align: 'center',
		valign: 'middle',
                events: operateEvents,
                formatter: operateFormatter,
            }, {
                field: 'bid',
                visible: false,
            },],
	    onReorderRowsDrag: function (table, row) {
	    	drag_prev = $(row).prev();
		drag_next = $(row).next();
		selected_index = parseInt(row.childNodes[0].innerHTML);
            },
	    onReorderRowsDrop: function (table, row) {
            	drop_prev = $(row).prev();
		drop_next = $(row).next();
		selected_row = row;
            },
	    onReorderRow: function (table, row) {
            	if(drop_prev.length == 0){
			if(drag_prev.length == 0){
				return;
			}
			selected_row.childNodes[0].innerHTML = "1";
			tb = document.getElementById("tb");
			for(i=1;i<parseInt(selected_index);i++){
				tb.rows[i+1].cells[0].innerHTML = parseInt(tb.rows[i+1].cells[0].innerHTML) + 1;
			}
		}
		else if(drop_next.length == 0){
			if(drag_next.length == 0){
				return;
			}
			selected_row.childNodes[0].innerHTML = table.length;
			tb = document.getElementById("tb");
			for(i=selected_index-1;i<parseInt(table.length-1);i++){
				tb.rows[i+1].cells[0].innerHTML = parseInt(tb.rows[i+1].cells[0].innerHTML) - 1;
			}
		}
		else{
			drag_prev_order = drag_prev.length ? parseInt(drag_prev[0].cells[0].innerHTML) : -1;
			drop_prev_order = parseInt(drop_prev[0].cells[0].innerHTML);
			drop_next_order = parseInt(drop_next[0].cells[0].innerHTML);
			if(drag_prev_order < drop_prev_order){
				selected_row.childNodes[0].innerHTML = drop_prev_order;
				tb = document.getElementById("tb");
				for(i=selected_index-1;i<drop_prev_order-1;i++){
					tb.rows[i+1].cells[0].innerHTML = parseInt(tb.rows[i+1].cells[0].innerHTML) - 1;
				}			
			}
			else if(drag_prev_order > drop_prev_order){
				selected_row.childNodes[0].innerHTML = drop_next_order;
				tb = document.getElementById("tb");
				for(i=drop_next_order;i<drag_prev_order+1;i++){
					tb.rows[i+1].cells[0].innerHTML = parseInt(tb.rows[i+1].cells[0].innerHTML) + 1;
				}			
			}
			else{
				return;
			}

		}
		reorder(table);
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            departmentname: $("#txt_search_departmentname").val(),
            statu: $("#txt_search_statu").val()
        };
        return temp;
    };
    return oTableInit;
};

function operateFormatter(value, row, index) {
        return [
            '<a class="edit" href="#" title="编辑信息">编辑</a>',
	    '|',
            '<a class="delete" href="#" title="删除业务">删除</a>',
        ].join('');
};

window.operateEvents = {
        'click .edit': function (e, value, row, index) {
		$('#name_e').val(row.name);
		$('#info_e').val(row.info);
		$('#details_e').val(row.details);
		$('#bid').val(row.bid);
		$('#pic_e').attr('src', row.picture);
		$("#EditModal").modal();
	},
        'click .delete': function (e, value, row, index) {
		bid = row.bid;
		$("#DeleteModal").modal();
        }
	
};

</script>
<script>
var state = -1;
var bid = '';
var reorder = function(tb){
	var data = "";
	for(i in tb){
		tr = tb[i];
		str = "bid=" + tr.bid + ",order=" + tr.order + ",index=" + i + ";";
		data += str;
	}
        $.ajax({
            url: "/business/other/reorder/",
            data: {'table': data, 'btype': "{{ btype }}" },
            type: "POST",
            dataType:"text",
            success: function(data) {

                json = eval("("+data+")");
		state = json.state;
                if(json.state === 0){
                    $("#tb").bootstrapTable('refresh', {'silent': true});
		}
                else{
                    $('#msg_icon').removeAttr('class');
		    $('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		    $('#msg').html("排序失败，" + json.msg);
                }
            },
	    error: function(xhr, error){
		state = -1;
		$('#msg_icon').removeAttr('class');
		$('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		$('#msg').html("排序失败，服务器发生错误");
	    }
        });
	if(state!=0){
	    $('#MsgModal').modal();
	}
	return;
};

var add_submit = function(){
        var data = {};
	data['name'] = $('#name').val();
	data['info'] = $('#info').val();
	data['details'] = $('#details').val();
	data['btype'] = $('#btype').val();
	data['pic'] = pic;
	$.ajax({
            url: "/business/other/add/",
            data: data,
            type: "POST",
            dataType:"text",
            success: function(data) {

                json = eval("("+data+")");
		state = json.state;
                if(json.state === 0){
                   $('#msg_icon').removeAttr('class');
		   $('#msg_icon').attr('class', 'glyphicon glyphicon-ok-sign');
		   $('#msg').html("添加成功");
                   $('#AddModal').modal('hide');
		   $('#name').val('');
		   $('#info').val('');
		   $('#details').val('');
		   $('#pic_pre').html('');
		   pic = '';
                }
                else{
                   $('#msg_icon').removeAttr('class');
		   $('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		   $('#msg').html("添加失败,"+json.msg);
                }
            },
	    error: function(xhr, error){
		state = -1;
		$('#msg_icon').removeAttr('class');
		$('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		$('#msg').html("添加失败，服务器发生错误");
	    }
        });
	$('#MsgModal').modal();
	return;
};

var edit_submit = function(){
        var data = {};
	data['name'] = $('#name_e').val();
	data['info'] = $('#info_e').val();
	data['details'] = $('#details_e').val();
	data['bid'] = $('#bid').val();
	data['pic'] = pic_e;
	$.ajax({
            url: "/business/other/edit/",
            data: data,
            type: "POST",
            dataType:"text",
            success: function(data) {

                json = eval("("+data+")");
		state = json.state;
		if(json.state === 0){
                   $('#msg_icon').removeAttr('class');
		   $('#msg_icon').attr('class', 'glyphicon glyphicon-ok-sign');
		   $('#msg').html("修改成功");
                   $('#EditModal').modal('hide');
		   pic = '';
                }
                else{
                   $('#msg_icon').removeAttr('class');
		   $('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		   $('#msg').html("修改失败,"+json.msg);
                }
                $('#MsgModal').modal();

            },
	    error: function(xhr, error){
		state = -1;
		$('#msg_icon').removeAttr('class');
		$('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		$('#msg').html("修改失败，服务器发生错误");
	    }
        });
	$('#MsgModal').modal();
	return;
};

var Del = function(){

	$.ajax({
            url: "/business/other/delete/",
            data: {'bid': bid},
            type: "POST",
            dataType:"text",
            success: function(data) {

                $('#DeleteModal').modal('hide');
                json = eval("("+data+")");
		state = json.state;
		if(json.state === 0){
                   $('#msg_icon').removeAttr('class');
		   $('#msg_icon').attr('class', 'glyphicon glyphicon-ok-sign');
		   $('#msg').html("删除成功");
                   bid = '';
		}
                else{
                   $('#msg_icon').removeAttr('class');
		   $('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		   $('#msg').html("删除失败,"+json.msg);
                }
            },
	    error: function(xhr, error){
		state = -1;
		$('#msg_icon').removeAttr('class');
		$('#msg_icon').attr('class', 'glyphicon glyphicon-remove-sign');
		$('#msg').html("删除失败，服务器发生错误");
	    }
        });
	$('#MsgModal').modal();
	return;
}

$(document).ready(function(){
	
	$('#MsgModal').on('hidden.bs.modal', function () {
		if(state === 0){
			$("#tb").bootstrapTable('refresh', {'silent': true});
		}
	});

	viewers.forEach(function(e){
		e.element=null;
	})
});

</script>
<script>
nav = document.getElementById("nav_{{ btype }}");
nav.setAttribute("class", "active");
</script>
{% endblock %}

